package com.bryant.bryant_weather

import android.util.SparseArray
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.viewpager2.adapter.FragmentStateAdapter
import com.bryant.miantong.ui.home.HomeFragment
import com.bryant.miantong.ui.interview.InterviewFragment
import com.bryant.miantong.ui.mine.MineFragment
import com.bryant.miantong.ui.project.ProjectFragment


class ViewPagerAdapter(fragmentActivity:FragmentActivity): FragmentStateAdapter(fragmentActivity) {

    // 使用SparseArray存储Fragment实例，key为position，value为Fragment
    private val fragmentCache = SparseArray<Fragment>()
    override fun createFragment(position: Int): Fragment {
        // 首先尝试从缓存中获取Fragment实例
        var fragment = fragmentCache.get(position)
        return if (fragment != null) {
            // 如果缓存中存在该Fragment实例，则直接返回
            fragment
        } else {
            // 创建新的Fragment实例并缓存起来
            fragment = when (position) {
                0 -> HomeFragment()
                1 -> ProjectFragment()
                2 -> InterviewFragment()
                3 -> MineFragment()
                else -> throw IllegalArgumentException("Invalid position: $position")
            }
            // 将创建的Fragment实例缓存起来
            fragmentCache.put(position, fragment)
            // 返回创建的Fragment实例
            fragment
        }
    }
    // 返回页面总数，这里固定为4个页面
    override fun getItemCount(): Int {
        return 4
    }
}